<?php 
namespace app\api\controller;

use app\common\controller\Common;
use think\Db;
use app\api\controller\Sensitive;

class SensitiveWord {
	protected static $Request;

	function __construct() {
		self::$Request = request()->param();
	}

	/**
	 * 添加敏感词 - Api
	 */
	public function createSensitiveWord() {
		try {
			$sid = self::$Request['sid'];
			$name = self::$Request['name'];
			$res = self::createSensitiveWordLogic($sid, $name);
			return JRes($res);
		} catch (Exception $e) {
			return resultArray(['error' => $e->getMessage()]);
		}
	}

	/**
	 * 批量添加敏感词 - Api
	 */
	public function batchCreateSensitiveWord() {
		try {
			$sid = self::$Request['sid'];
			$nameArr = json_decode(self::$Request['name_arr'], true);
			$res = self::batchCreateSensitiveWordLogic($sid, $nameArr);
			return JRes($res);
		} catch (Exception $e) {
			return resultArray(['error' => $e->getMessage()]);
		}
	}

	/**
	 * 查询敏感词 - Api
	 */
	public function selectSensitiveWord() {
		try {
			$sid = self::$Request['sid'];
			$whereCondt = [
				Model('SensitiveWord')::SID => $sid
			];
			$res = self::selectSensitiveWordLogic($whereCondt);
			return resultArray(['data' => $res->data]);
		} catch (Exception $e) {
			return resultArray(['error' => $e->getMessage()]);
		}
	}

	/**
	 * 删除敏感词 - Api
	 */
	public function deleteSensitiveWord() {
		try {
			$id = self::$Request['id'];
			$whereCondt = [
				Model('SensitiveWord')::ID => $id
			];
			$res = self::deleteSensitiveWordLogic($whereCondt);
			return JRes($res);
		} catch (Exception $e) {
			return resultArray(['error' => $e->getMessage()]);
		}
	}

	/**
	 * 批量删除敏感词 - Api
	 */
	public function batchDeleteSensitiveWord() {
		try {
			$idArr = json_decode(self::$Request['id_arr'], true);
			$res = self::batchDeleteSensitiveWordLogic($idArr);
			return JRes($res);
		} catch (Exception $e) {
			return resultArray(['error' => $e->getMessage()]);
		}
	}

	// 添加敏感词 - Logic
	public static function createSensitiveWordLogic($sid, $name) {
		// 敏感词是否存在
		$res = self::validateWordIsExist($sid, $name);
		if ($res->isSuccess) { return operationRes(false, $res->info); }

		// 添加敏感词
		return self::createSensitiveWordCore($sid, $name);
	}

	/**
	 * 更新words
	 */
    public function updateSensitiveWords() {
        try {
        	$sid = self::$Request['sid'];
            $nameArr = json_decode(self::$Request['name_arr'], true);
            $res = self::updateSensitiveWordsLogic($sid, $nameArr);
            if ($res->isSuccess) {
            	Sensitive::updateSensitiveUpdateTimeLogic($sid);
            }
            return JRes($res);
        } catch (Exception $e) {
            return resultArray(['error' => $e->getMessage()]);
        }
    }

    // 更新敏感词 - Logic
    public static function updateSensitiveWordsLogic($sid, $nameArr) {
    	// 删除 $sid 的敏感词
    	$whereCondt = [
    		Model('SensitiveWord')::SID => $sid
    	];
    	$res = self::deleteSensitiveWordLogic($whereCondt);

    	// 添加新敏感词
    	$res = self::batchCreateSensitiveWordLogic($sid, $nameArr);

    	// 更新敏感词树
        $res = Sensitive::updateSensitiveTreeLogic();
    	return $res;
    }

	/**
	 * 批量添加敏感词 - Logic
	 * @param isRepeat false-不可重复,true-可重复 | 默认false
	 */
	public static function batchCreateSensitiveWordLogic($sid, $nameArr, $isRepeat=false) {
		if (!$isRepeat) {
			$nameArr = array_unique($nameArr);
		}

		$newArr = [];
		foreach ($nameArr as $key => $val) {
			if ($val=='') {
				continue;
			}

			$curArr = [
				Model('SensitiveWord')::SID => $sid,
				Model('SensitiveWord')::NAME => $val,
			];

			// 去重
			if (!$isRepeat) {
				$res = self::validateWordIsExist($sid, $val);
				if (!$res->isSuccess) {
					// 不存在，可添加
					array_push($newArr, $curArr);
				}
			}else {
				array_push($newArr, $curArr);
			}
		}
		return self::batchCreateSensitiveWordCore($newArr);
	}

	// 查询敏感词 - Logic
	public static function selectSensitiveWordLogic($whereCondt) {
		return self::selectSensitiveWordCore($whereCondt);
	}

	// 删除敏感词 - Logic
	public static function deleteSensitiveWordLogic($whereCondt) {
		return self::deleteSensitiveWordCore($whereCondt);
	}

	// 批量删除敏感词 - Logic
	public static function batchDeleteSensitiveWordLogic($idArr) {
		return self::batchDeleteSensitiveWordCore($idArr);
	}

	// 敏感词是否存在 - Validate
	public static function validateWordIsExist($sid, $name) {
		$whereCondt = [
			Model('SensitiveWord')::SID => $sid,
			Model('SensitiveWord')::NAME => $name
		];
		$res = self::selectSensitiveWordLogic($whereCondt);
		if (!empty($res->data->list)) {
			return operationRes(true, lang('exist'), $res->data->list[0]);
		}else {
			return operationRes(false, lang('not_exist'));
		}
	}

	// 查询出更新中的文件下的词 - Logic
	public static function selectWordsByUpdatingSensitiveLogic() {
		$list = Model('SensitiveWord')::hasWhere('sensitive', ['status' => 2])->select();
		return operationRes(true, lang('query_successful'), ['list' => $list]);
	}

	// 添加敏感词 - Core
	private static function createSensitiveWordCore($sid, $name) {
		if ($name=='') {
			return operationRes(false, lang('add_failed'));
		}

		$timestamp = time();
		$createData = [
			Model('SensitiveWord')::SID => $sid,
			Model('SensitiveWord')::NAME => $name,
			Model('SensitiveWord')::CREATE_TIME => $timestamp,
			Model('SensitiveWord')::UPDATE_TIME => $timestamp

		];
		if ($res = Model('SensitiveWord')::create($createData)) {
			return operationRes(true, lang('add_successful'), $res);
		}else {
			return operationRes(false, lang('add_failed'));
		}
	}

	// 批量添加敏感词 - Core
	private static function batchCreateSensitiveWordCore($arr) {
		$timestamp = time();
		if (!empty($arr)) {
			foreach ($arr as $key => $val) {
				$arr[$key][Model('SensitiveWord')::CREATE_TIME] = $timestamp;
				$arr[$key][Model('SensitiveWord')::UPDATE_TIME] = $timestamp;
			}
		}
		
		if ($res = Model('SensitiveWord')::insertAll($arr)) {
			return operationRes(true, lang('add_successful'), $res);
		}else {
			return operationRes(false, lang('add_failed'));
		}
	}

	// 查询敏感词 - Core
	private static function selectSensitiveWordCore($whereCondt) {
		// 查询
		$list = Model('SensitiveWord')::where($whereCondt)->field(['id', 'name'])->select();

		// 返回结果
  		$returnData = [
  			'list' => $list
  		];
  		return operationRes(true, lang('query_successful'), $returnData);
	}

	// 删除敏感词 - Core
	private static function deleteSensitiveWordCore($whereCondt) {
		if (Model('SensitiveWord')::where($whereCondt)->delete()) {
			return operationRes(true, lang('delete_successful'));
		}else {
			return operationRes(false, lang('delete_failed'));
		}
	}

	// 批量删除敏感词 - Core
	private static function batchDeleteSensitiveWordCore($idArr) {
		if (Model('SensitiveWord')::destroy($idArr)) {
			return operationRes(true, lang('delete_successful'));
		}else {
			return operationRes(false, lang('delete_failed'));
		}
	}
}